package dbb

import (
	"bytes"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/y2h/fyne_poem/widgets"
)

func sqlui(db gdb.DB) {
	w := widgets.EmptyWin("Sql query")

	top := widget.NewMultiLineEntry()
	top.SetText("select * from menu limit 5;")
	dl := binding.NewStringList()
	lst := widget.NewListWithData(dl, func() fyne.CanvasObject {
		return widget.NewLabel("no data")
	}, func(di binding.DataItem, co fyne.CanvasObject) {
		lbl := co.(*widget.Label)
		lbl.Bind(di.(binding.String))
	})
	msg := widget.NewLabel("")
	btn := widget.NewButton("Do", func() {
		dl.Set([]string{})
		if db == nil {
			msg.SetText("no db connected, close this window and connect a db , then open this window")
			return
		}
		eng := gf2xorm(db)
		bf := bytes.NewBufferString(top.Text)
		rs, err := eng.Import(bf)
		if err != nil {
			Me.Msg.SetText(err.Error())
			return
		}
		for _, v := range rs {
			ra, _ := v.RowsAffected()
			dl.Set([]string{gconv.String(ra)})
		}
		eng.CreateTables()
		// sqlstr := strings.TrimSpace(top.Text)
		// sqls := strings.Split(sqlstr, ";")
		// for _, s := range sqls {
		// 	rs, err := db.Query(db.GetCtx(), strings.TrimSpace(s))
		// 	if err != nil {
		// 		msg.SetText("error occur,please see the log")
		// 		menu.Glog.Error(Ctx, err)
		// 		return
		// 	}
		// 	for _, v := range rs {
		// 		dl.Append(v.Json())
		// 	}
		// }
	})
	split := container.NewVSplit(top, lst)
	cc := container.NewBorder(btn, msg, nil, nil, split)
	w.SetContent(cc)
	w.Show()
}
